/**
 * 
 */
package com.ditty.handler;

import java.io.File;
import java.io.IOException;

import com.ditty.HttpConfiguration;
import com.ditty.invoke.handler.HandlerInvoker;
import com.ditty.kit.FileKit;
import com.ditty.kit.HttpKit;
import com.ditty.kit.StrKit;
import com.ditty.kit.ValueKit;

/**
 * @author dingnate
 *
 */
public class ResourceHandler extends AbstractHttpHandler {
	/**
	 * @param webDir
	 */
	public ResourceHandler() {
		super();
	}

	@Override
	public void handle(HandlerInvoker invoker) {
		int rIndex;
		if ((rIndex = StrKit.lastIndexOf(invoker.getTarget(), ValueKit.STR_DOT)) == -1) {
			invoker.handle();
		} else {
			File file = new File(HttpConfiguration.me().getWebDir(), invoker.getTarget());
			if (!file.exists()) {
				invoker.getHttpResponseWrapper().setStatusCode(HttpKit.STATUS_404);
				return;
			}
			try {
				invoker.getHttpResponseWrapper()
						.headers()
						.put(HttpKit.HEADER_CONTENTTYPE,
								HttpKit.getContentType(invoker.getTarget().substring(rIndex + 1).toLowerCase()) + "; charset="
										+ HttpConfiguration.me().getEncoding());
				invoker.getHttpResponseWrapper().write(FileKit.readFile(file));
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
